package com.es.spring_es.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.es.spring_es.model.vo.SearchResult;
import com.es.spring_es.utils.HttpRequester;
import com.es.spring_es.utils.HttpRespons;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;

/**
 * @author xu
 * @date 2020/6/3
 * @desciption 高德数据服务
 */
@Service
public class GaodeServices {

    public static String key = "f3dca6feeef3b0faae92623638d114e7";

    public static String sid = "87797";

    private static Logger logger = LogManager.getLogger(GaodeServices.class);

    HttpRequester httpRequester = new HttpRequester();

    public SearchResult trsearch(String tid, String trid, boolean correction, Integer page, Integer pageSize){

        logger.info("geting track, trid: "+trid+" ,tid: "+tid);

        String url = "https://tsapi.amap.com/v1/track/terminal/trsearch";

        HashMap<String, String> params = new HashMap<>();
        params.put("key", key);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trid",trid);


        //不纠偏，默认纠偏
        if (!correction){
            params.put("correction","denoise=0,mapmatch=0,attribute=0,threshold=0,mode=driving");
        }

        if (page==null||page<=0){
            page=1;
        }
        if (pageSize==null||pageSize<=0){
            pageSize=999;
        }

        params.put("page",page.toString());
        params.put("pagesize",pageSize.toString());


        SearchResult searchResult=null;

        HttpRespons httpRespons = null;
        try {
            httpRespons = httpRequester.sendPost(url, params);
        } catch (IOException e) {
            logger.error("获取trid轨迹失败" + e.getMessage(), e);
            e.printStackTrace();
            //throw  new RequestException(1,"获取trid轨迹失败: " + e.getMessage());
        }

        String content = httpRespons.getContent();
        HashMap resultMap = JSON.parseObject(content, new TypeReference<HashMap>(){});
        Integer code = (Integer)resultMap.get("errcode");

        if (code!=10000) {
            String errmsg = (String) resultMap.get("errmsg");
            String errdetail = (String) resultMap.get("errdetail");
            logger.error("errmsg -->  "+errmsg+"  errdetail -->  "+errdetail);
           // throw  new RequestException(1,errmsg+"   " + errdetail);
        }

        JSONObject data = (JSONObject) resultMap.get("data");
        if (data==null){
            logger.error("data is null");
            //throw  new RequestException(1,"data is null");
        }

        //条数
        searchResult = JSON.toJavaObject(data, SearchResult.class);
        logger.info("get  track  success, trid: "+trid);
        return searchResult;
    }



}
